package com.zhaojonhy.zhaopangwb.utils;

import android.text.format.DateFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by Administrator on 2016/9/19.
 */
public class DateUtils {
    // "created_at": "Mon Sep 19 14:05:45 +0800 2016"

    public static final long ONE_MINUTE_MILLIONS = 60*1000 ;
    public static final long ONE_HOUR_MILLIONS = 60*ONE_MINUTE_MILLIONS ;
    public static final long ONE_DAY_MILLIONS = 24*ONE_HOUR_MILLIONS ;

    public static String getShortTime(String dateStr){
        String str = "" ;
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy" , Locale.US) ;//日期规则
        try {
            Date date = sdf.parse(dateStr) ;
            Date curDate = new Date() ;//获取当前时间
            //利用毫秒值进行差值的比较
            long durTime = curDate.getTime() - date.getTime() ;
            int dayStatus = caculateDayStatus(date,curDate) ;
            if(durTime < ONE_MINUTE_MILLIONS){
                str = "刚刚" ;
            }else if(durTime < ONE_HOUR_MILLIONS){
                str = durTime / ONE_MINUTE_MILLIONS +"分钟前";
            }else if( dayStatus == 0 ){
                str = durTime / ONE_HOUR_MILLIONS +"小时前";
            }else if( dayStatus == -1 ) {
                str = "昨天" + DateFormat.format("HH:mm", date);
//                同一年显示月日，不同年显示年月日
            }else if( isSameYear(date,curDate) && dayStatus < -1){//同一年并且是昨天或者更早
                str = DateFormat.format("MM-dd", date)+"";
            }else {//非同年
                str = DateFormat.format("yyyy-MM-dd", date)+"";
            }
        }catch (ParseException e){
            e.printStackTrace();
        }
        return str ;
    }

    //判断是否同年的方法
    public static boolean isSameYear(Date targetTime , Date compareTime){
        Calendar tarCalendar = Calendar.getInstance() ;
        tarCalendar.setTime(targetTime);
        int tarYear = tarCalendar.get(Calendar.YEAR) ;//Calendar可以利用get获取年月日，这里获取天数

        Calendar compareCalendar = Calendar.getInstance() ;
        compareCalendar.setTime(compareTime);
        int compareYear = compareCalendar.get(Calendar.YEAR) ;//Calendar可以利用get获取年月日，这里获取天数

        return tarYear == compareYear;
    }

    //用日历来判断天，如凌晨01:00，那两个小时前就是昨天了
    //把当前的时间和比较的时间进行判断
    public static int caculateDayStatus(Date targetTime , Date compareTime){
        Calendar tarCalendar = Calendar.getInstance() ;
        tarCalendar.setTime(targetTime);
        int tarDayOfYear = tarCalendar.get(Calendar.DAY_OF_YEAR) ;//Calendar可以利用get获取年月日，这里获取天数

        Calendar compareCalendar = Calendar.getInstance() ;
        compareCalendar.setTime(compareTime);
        int compareDayOfYear = compareCalendar.get(Calendar.DAY_OF_YEAR) ;//Calendar可以利用get获取年月日，这里获取天数

        return tarDayOfYear - compareDayOfYear ;
    }
}
